package com.gopay.bis.khpay.ebank.operation;

import java.math.BigDecimal;

import org.apache.axis.utils.StringUtils;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.ecc.emp.data.IndexedCollection;
import com.ecc.emp.data.KeyedCollection;
import com.gopay.bis.common.util.BankLogUtils;
import com.gopay.common.constants.proccode.ProcCodeConstants;
import com.gopay.common.domain.bank.khpay.ebank.KhPayMessage;
import com.gopay.common.exception.GopayException;
import com.sdb.payclient.core.PayclientInterfaceUtil;

/**
 * 平安跨行支付退款接口
 * 
 * @KhPayRefund.java
 * @author zhengxue
 * @2017-8-18 下午4:17:24 www.gopay.com.cn Inc.All rights reserved.
 */
public class KhPayRefund {
    protected Logger log = LoggerFactory.getLogger(KhPayRefund.class);

    /**
     * 退款接口
     * 
     * @param object
     * @return
     * @throws GopayException
     */
    public Object refund(Object object) throws GopayException {
        KhPayMessage message = (KhPayMessage) object;
        try {
            log.error("KhPayRefund req: " + ToStringBuilder.reflectionToString(message));
            PayclientInterfaceUtil util = new PayclientInterfaceUtil();
            KeyedCollection input = new KeyedCollection("input");
            KeyedCollection output = new KeyedCollection("output");
            input.put("masterId", message.getMasterId());
            input.put("refundNo", message.getBankOrderId());
            input.put("orderId", message.getTkOriBankOrderId());
            input.put("currency", message.getCurrency());
            input.put("refundAmt", message.getAmount().toString());
            input.put("remark", message.getRemark());
            input.put("objectName", message.getObjectName());
            input.put("NOTIFYURL", message.getNotifyUrl());

            output = util.execute(input, message.getTransCode());
            String errorCode = (String) output.getDataValue("errorCode");
            String errorMsg = (String) output.getDataValue("errorMsg");

            if (StringUtils.isEmpty(errorCode) && StringUtils.isEmpty(errorMsg)) {
                // 退款受理成功
                message.setStatus((String) output.getDataValue("status"));
                message.setMasterId((String) output.getDataValue("masterId"));
                message.setRefundAmt(String.valueOf(output.getDataValue("refundAmt")));
                message.setBankOrderId((String) output.getDataValue("refundNo"));
                message.setCurrency(String.valueOf(output.getDataValue("currency")));
            } else {
                // 退款失败
                message.setErrorCode(errorCode);
                message.setErrorMsg(errorMsg);
            }
            log.error("KhPayRefund res: " + ToStringBuilder.reflectionToString(message));
        } catch (Exception e) {
            BankLogUtils.printRefundExceptionLog(message, e);
            throw new GopayException(ProcCodeConstants.PROC_CODE_100E6087);
        }

        return message;
    }

    /**
     * 退款查询接口
     * 
     * @param object
     * @return
     * @throws GopayException
     */
    public Object queryRefund(Object object) throws GopayException {
        KhPayMessage message = (KhPayMessage) object;
        try {
            log.error("KhPayRefund query req: " + ToStringBuilder.reflectionToString(message));
            PayclientInterfaceUtil util = new PayclientInterfaceUtil();
            KeyedCollection input = new KeyedCollection("input");
            KeyedCollection output = new KeyedCollection("output");
            input.put("masterId", message.getMasterId());
            input.put("beginDate", message.getBeginDate());
            input.put("endDate", message.getEndDate());

            output = util.execute(input, message.getTransCode());
            String errorCode = (String) output.getDataValue("errorCode");
            String errorMsg = (String) output.getDataValue("errorMsg");

            if (StringUtils.isEmpty(errorCode) && StringUtils.isEmpty(errorMsg)) {
                // 退款查询成功
                IndexedCollection orderList = (IndexedCollection) output.getDataElement("iOrderListDetail");
                for (int i = 0; i < orderList.size(); i++) {
                    KeyedCollection orderDetail = (KeyedCollection) orderList.getElementAt(i);
                    String bankOrderId = (String) orderDetail.getDataValue("refundNo");
                    if (message.getBankOrderId().equals(bankOrderId)) {
                        System.out.print("---商户号---"+orderDetail.getDataValue("masterId"));
                        System.out.print("---退款单号---"+orderDetail.getDataValue("refundNo"));
                        System.out.print("---原订单号---"+orderDetail.getDataValue("orderId"));
                        System.out.print("---退款请求接收时间---"+orderDetail.getDataValue("refundTime"));
                        System.out.print("---币种---"+orderDetail.getDataValue("currency"));
                        System.out.print("---退款金额---"+orderDetail.getDataValue("refundAmt"));
                        System.out.print("---退款状态---"+orderDetail.getDataValue("refundStatus"));  //01成功；02失败；00处理中
                        System.out.print("---退款本金扣收标志---"+orderDetail.getDataValue("settleflg"));  //0：未扣款；1：已扣款；2：扣款中
                        System.out.print("---退款失败本金退还标志---"+orderDetail.getDataValue("refundFlag"));  //0：未退款；1：已退款；2：处理中
                        System.out.print("---错误码---"+orderDetail.getDataValue("errorCode"));  //1已清算，0待清算
                        System.out.println("---错误说明---"+orderDetail.getDataValue("errorMsg"));
                        
                        message.setTkOriBankOrderId((String) orderDetail.getDataValue("orderId"));
                        message.setRefundStatus((String) orderDetail.getDataValue("refundStatus"));
                        message.setRefundAmt(String.valueOf(orderDetail.getDataValue("refundAmt")));
                        message.setRefundTime((String) orderDetail.getDataValue("refundTime"));
                        message.setSettleflg((String) orderDetail.getDataValue("settleflg"));// 0：未扣款；1：已扣款；2：扣款中
                        message.setRefundFlag((String) orderDetail.getDataValue("refundFlag")); // 0：未退款；1：已退款；2：处理中
                        break;
                    }
                }
            } else {
                // 退款查询失败
                message.setErrorCode(errorCode);
                message.setErrorMsg(errorMsg);
            }
            log.error("KhPayRefund query res: " + ToStringBuilder.reflectionToString(message));
        } catch (Exception e) {
            BankLogUtils.printRefundExceptionLog(message, e);
            throw new GopayException(ProcCodeConstants.PROC_CODE_100E6087);
        }

        return message;
    }
}
